package cx3k.dataAccess.test;

import java.util.Scanner;

public class Util {
	
	public static void printHeader(String msg){
		//					12345678901234567890123456789012345678901234567890123456789012345678901234567890		
		System.out.println("\n\n");
		System.out.println("+----------------------------------------------------------+");
		System.out.printf("| %-56s |\n", msg.toUpperCase());
		System.out.println("+----------------------------------------------------------+");
	}
	
	/**
	 * 
	 * @param min The minimum value requested (inclusive)
	 * @param max The maximum value requested (inclusive)
	 * @param msg The message to be displayed
	 * @return The integer input from the user
	 */
	public static int getValidInt(int min, int max, String msg){
		
		String input = getInput(msg);
		
		try{
			int formatted = Integer.parseInt(input);
			
			if(formatted > max || formatted < min){
				throw new NumberFormatException();
			}
			
			return formatted;
			
		} catch(NumberFormatException ex){
			System.err.println("Invalid input (\"" + input + "\").  Expected an integer between " + min + " and " + max + ".");
			return getValidInt(min, max, msg);
		} 
	}
	
	public static int getValidInt(int min, String msg){
		
		String input = getInput(msg);
		
		try{
			int formatted = Integer.parseInt(input);
			
			if(formatted < min){
				throw new NumberFormatException();
			}
			
			return formatted;
			
		} catch(NumberFormatException ex){
			System.err.println("Invalid input (\"" + input + "\").  Expected an integer greater than " + min + ".");
			return getValidInt(min, msg);
		} 
	}
	
	public static boolean getYesNo(String msg){
		
		String input = getInput(msg + " (y/n)");
		
		try{
			if(input.length() > 1){
				throw new Exception();
			}
			
			input = input.toLowerCase();
			
			if(input.charAt(0) == 'y'){
				return true;
			} else if(input.charAt(0) == 'n'){
				return false;
			} else {
				throw new Exception();
			}
		} catch(Exception ex){
			System.err.println("Invalid input (\"" + input + "\").  Expected 'y' (yes) or 'n' (no).");
			return getYesNo(msg);
		}
	}
	
	/**
	 * 
	 * @param msg The message to be displayed to the user
	 * @return The input returned (one line)
	 */
	public static String getInput(String msg){
		System.out.print("\n" + msg + ": ");
		return new Scanner(System.in).nextLine();
	}

}
